<?php

namespace app\controller;


use app\BaseController;
use app\Request;
use app\Result;
use DateTime;
use think\facade\Db;
use think\response\Json;
use think\db\exception\DbException;
use app\Exceptions\CustomException;

class OutLog extends BaseController
{

    /**
     * @param Request $request
     * @return Json
     * @throws DbException
     */
    public function addOutLog(Request $request): Json
    {

        $dateTime = new DateTime();
        $data = [
            "commodity_id" => $request->post("commodity_id"),
            "num" => $request->post("num"),
            "price" => $request->post("price"),
            "customer" => $request->post("customer"),
            "count_price" => $request->post("count_price"),
            "out_time" => $dateTime->format("Y-m-d H:i:s"),
            "state"=>1
        ];

        validate(\app\validate\OutLog::class)->check($data);

        Db::name("out_log")->save($data);

        Db::name("commodity")->where("commodity_id", $data["commodity_id"])->dec("num", $data["num"])->update();

        return Result::success(null,"出库成功");
    }

    /**
     * @throws DbException
     * @throws CustomException
     */
    public function getOutLogList(Request $request): Json
    {
        $commodity_id = $request->post("commodity_id");
        $pageSize = $request->post("pageSize");
        $pageNo = $request->post("pageNo");

        if (!$commodity_id) {
            throw new CustomException(10001, "请输入商品ID");
        }

        $resultData = Db::name("out_log")->where("commodity_id", $commodity_id)->paginate([
            'list_rows' => $pageSize,
            'page' => $pageNo,
        ]);

        return Result::success($resultData);
    }


    /**
     * @param Request $request
     * @return Json
     * @throws DbException
     */
    public function delLog(Request $request): Json
    {
        $id = $request->param("id");
        $dateTime=new DateTime();
        Db::name("out_log")->where("id", $id)->data([
            "state"=>0,
            "return_time"=>$dateTime->format("Y-m-d H:i:s")
        ])->update();
        $log=Db::name("out_log")->where("id", $id)->find();
        Db::name("commodity")->where("commodity_id",$log['commodity_id'])->inc("num",$log['num'])->update();
        return Result::success(null,"退货成功！");
    }
}